package com.thinkfit.jy.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;

import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.AppUtils;
import com.common.lib.utils.LogUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SystemUtils {

    /**
     * appName
     */
    public static String APPNAME = "JYDownload";
    public static String TAG = "SystemUtils------------------>";
    private static SystemUtils systemUtils;

    public static SystemUtils getInstance(){
        if(systemUtils == null){
            systemUtils = new SystemUtils();
        }
        return systemUtils;
    }

    // 根据亮度值修改当前window亮度
    public static void changeAppBrightness(Context context, int brightness) {
        Window window = ((Activity) context).getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    /**
     *获取系统最大屏幕亮度
     */
    public static int getMaxBrightness(Context context) {
        int brightnessSettingMaximumId = context.getResources().getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android");
        int brightnessSettingMaximum = context.getResources().getInteger(brightnessSettingMaximumId);
        return brightnessSettingMaximum;
    }

    /**
     *获取系统屏幕亮度
     */
    public static int getBrightness(Context context) {
        int brightness = -1;
        ContentResolver resolver = context.getContentResolver();
        try {
            brightness = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return brightness;
    }

    /**
     * 应用置顶
     * @param context
     */
    public static void setTopApp(Context context,String packageName) {
        if (!isForeground(context,packageName)) {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            //获得当前运行的task(任务)
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                LogUtil.LogE("ddddddddddddddddddddddd    pid  进程Task：" + taskInfo.topActivity.getPackageName());
                //找到本应用的 task，并将它切换到前台
                if (taskInfo.topActivity.getPackageName().equals(packageName)) {
                    activityManager.moveTaskToFront(taskInfo.id, 0);
                    break;
                }
            }
        }
    }

    /**
     * 是否已经位于前台
     * @param context
     * @return
     */
    public static boolean isForeground(Context context,String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();
        if (appProcessInfoList != null && appProcessInfoList.size() > 0) {
            //枚举进程
            for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfoList) {
                if (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    if (appProcessInfo.processName.equals(packageName)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean isAppRunning(Context context,String packageName){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        if(runningAppProcesses != null){
            for (ActivityManager.RunningAppProcessInfo info : runningAppProcesses){
                if(info.processName.equals(packageName)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取版本号
     * @param context
     * @param packageName
     * @return
     */
    public static int getVersion(Context context, String packageName){
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getVersionName(Context context, String packageName){
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 安装apk（非静默安装）
     * @param apkFile
     */
    public void installApk(Context context,File apkFile) {
//        try {
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                Uri apkUri = FileProvider.getUriForFile(this, AppUtils.getAppPackageName() + ".fileprovider", apkFile);
//                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//            } else {
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                Uri uri = Uri.fromFile(apkFile);
//                intent.setDataAndType(uri, "application/vnd.android.package-archive");
//            }
//            startActivity(intent);
//        } catch (Exception e) {
//        }

//        Uri apkUri = FileProvider.getUriForFile(this, AppUtils.getAppPackageName() + ".fileprovider", apkFile);
//        Intent install = new Intent(Intent.ACTION_VIEW);
//        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
//        install.putExtra("silent_install", true); // 静默安装
//        context.startActivity(install);
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   apkFile : "+apkFile.getPath());
                boolean result = false;
                BufferedReader es = null;
                DataOutputStream os = null;

                try {
                    Process process = Runtime.getRuntime().exec("su");
                    os = new DataOutputStream(process.getOutputStream());

                    String command = "pm install -r " + apkFile.getAbsolutePath() + "\n";
                    os.write(command.getBytes(Charset.forName("utf-8")));
                    os.flush();
                    os.writeBytes("exit\n");
                    os.flush();

                    process.waitFor();
                    es = new BufferedReader(new InputStreamReader(process.getErrorStream()));

                    String line;
                    StringBuilder builder = new StringBuilder();
                    while ((line = es.readLine()) != null) {
                        builder.append(line);
                    }
                    Log.d(TAG, "install msg is " + builder.toString());

        /* Installation is considered a Failure if the result contains
            the Failure character, or a success if it is not.
             */
                    if (!builder.toString().contains("Failure")) {
                        result = true;
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            Uri apkUri = FileProvider.getUriForFile(context, AppUtils.getAppPackageName() + ".fileprovider", apkFile);
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                        } else {
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            Uri uri = Uri.fromFile(apkFile);
                            intent.setDataAndType(uri, "application/vnd.android.package-archive");
                        }
                        context.startActivity(intent);
                    } catch (Exception e1) {
                    }
                } finally {
                    try {
                        if (os != null) {
                            os.close();
                        }
                        if (es != null) {
                            es.close();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }
        }).subscribeOn(Schedulers.io())
                        .subscribe(new Observer<Object>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Object o) {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });


    }

    private static Runtime runtime;
    public static  void sendBack() {
        try {
            if (runtime == null)
                runtime = Runtime.getRuntime();
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static  void sendUp() {
        try {
            if (runtime == null)
                runtime = Runtime.getRuntime();
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_DPAD_UP);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static  void sendDown() {
        try {
            if (runtime == null)
                runtime = Runtime.getRuntime();
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_DPAD_DOWN);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static  void sendLeft() {
        try {
            if (runtime == null)
                runtime = Runtime.getRuntime();
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_DPAD_LEFT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getIp(Context context){
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = String.format("%d.%d.%d.%d",
                (ipAddress & 0xff),
                (ipAddress >> 8 & 0xff),
                (ipAddress >> 16 & 0xff),
                (ipAddress >> 24 & 0xff));

        return ip;
    }

    public static  void sendRight() {
        try {
            if (runtime == null)
                runtime = Runtime.getRuntime();
            runtime.exec("input keyevent " + KeyEvent.KEYCODE_DPAD_RIGHT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static  void sendCenter() {
        try {
            if (runtime == null)
                runtime = Runtime.getRuntime();
            runtime.exec("input keyevent " +  KeyEvent.KEYCODE_DPAD_CENTER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 重启应用
     * @param context
     */
    public void restartApp(Context context) {
        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 半秒钟后重启应用
        System.exit(0);
//        Intent intent = new Intent(getContext(), MainActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        getContext().startActivity(intent);
//        android.os.Process.killProcess(android.os.Process.myPid());
    }


    /**
     * 获取总存储空间
     * @return
     */
    public static long getTotalExternalMemorySize() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        StatFs stat = new StatFs(path);
        long blockSize = stat.getBlockSizeLong();
        long totalBlocks = stat.getBlockCountLong();
        return totalBlocks * blockSize; // 返回总大小，单位字节
    }

    /**
     * 获取可用存储空间
     * @return
     */
    public static long getAvailableExternalMemorySize() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        StatFs stat = new StatFs(path);
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        return availableBlocks * blockSize; // 返回可用大小，单位字节
    }

    /**
     * 获取可用内存
     *
     * @return
     */
    public static long getAvailableMemory(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo.availMem; // 获取可用内存，单位为字节
    }

    /**
     * 获取总内存
     * @return
     */
    public static long getTotalMemory() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/meminfo"), 8 * 1024);
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("MemTotal")) {
                    String[] columns = line.split("\\s+");
                    return Long.parseLong(columns[1]) * 1024; // 将kB转换为Bytes
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return -1; // 如果无法获取，返回-1
    }

    public static String bytesToKb(long bytes) {
        return (bytes / 1024) + " KB";
    }

    public static String bytesToMb(long bytes) {
        return (bytes / 1024 / 1024) + " MB";
    }

    public static String bytesToGb(long bytes) {
        return (bytes / 1024 / 1024 / 1024) + " GB";
    }

}
